﻿function HtmlEncode(text) {
    return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
function FormatText(text) {
    return HtmlEncode(text).replace(/\n/g, '<br />');
}
function GetRandomNumber() {
    return Math.floor(Math.random() * 10000);
}
function GetLogicalText(count, textToUse) {
    if (count > 1)
        return "+" + count + " " + textToUse + "s"
    else if (count < 0) {
        if (count == -1)
            return count + " " + textToUse;
        else// if (count < -1)
            return count + " " + textToUse + "s";
    }
    else if (count == 0)
        return "0 " + textToUse + "s";
    else
        return "+1 " + textToUse;
}

/*Modal Popup Section Starts */
var _PopupID;
var _PopupTitle;
var _PopupMessage;
var _CreateBlockingContainer = true;
var _ShadowIncreaseValue = 8;

function ShowModalPopup(popupId, title, message, createBlockingContainer) {
    _PopupID = popupId,
    _PopupTitle = title;
    _PopupMessage = message;
    _CreateBlockingContainer = createBlockingContainer;

    //SetModalPopupPosition();
    SetTexts();
    $('#' + _PopupID).Center().fadeIn('slow', ShowShadowContainer);
    //ShowShadowContainer();
    //CreteBlockingContainer();   
    //ShowShadowContainer();     
}
function SetTexts() {
    if (_PopupTitle.length > 0)
        $('#popupHeader').html(_PopupTitle);
    //$('#popupMessage').html(_PopupMessage);
}
function ShowShadowContainer() {
    if (null == document.getElementById(_PopupID)) return;
    var popup = $('#' + _PopupID);
    //var position = popup.position();    
    //var domElement = String.format('<div id="divShadow" class="modalpopupshadow" style="width:{0}px; height:{1}px;">&nbsp;</div>', popup.width() + (increaseValue * 2), popup.height() + (increaseValue * 2));
    var domElement = '<div id="divShadow" class="modalpopupshadow" style="width:' + (popup.width() + (_ShadowIncreaseValue * 2)) + 'px; height:' + (popup.height() + (_ShadowIncreaseValue * 2)) + 'px;">&nbsp;</div>';
    popup.parent().append(domElement);
    if(_CreateBlockingContainer)
        $('#divShadow').Center().fadeIn('slow', CreteBlockingContainer);
    else
        $('#divShadow').Center().fadeIn('slow', null);
}
function HideModalPopup() {
    if (null == document.getElementById(_PopupID)) return;
    $('#' + _PopupID).fadeOut(500, hideBlocking);
    $('#divShadow').fadeOut(500, RemoveShadeElement);
    return false;
}
function hideBlocking() {
    //$("#divBlockingContainer").css({'display' : 'none'});
    $('#divBlockingContainer').remove();
}
function RemoveShadeElement() {
    $('#divShadow').remove();
    //$('#divPopupButtonContainer').html('<input type="button" value="Ok" class="ButtonCommon" style="padding-right:0px; width:55px;" onclick="HideConfirmationPopup(\'confirm\');" />');
}
function CreteBlockingContainer() {
    var documentHeight = $(document).height();
    var documentWidth = $(document).width();
    documentWidth = $.browser.msie ? (documentWidth - 22) : documentWidth;
    documentHeight = $.browser.msie ? (documentHeight - 6) : documentHeight;
    var html = '<div id="divBlockingContainer" class="blockingContainer" style="position:absolute; z-index:19; width: ' + documentWidth + 'px; height: ' + documentHeight + 'px; left: 0px; top: 0px;"></div>';
    $('body').append(html);
    $('#divBlockingContainer').show();
}

///Reset the position of the Popup  
//window.onresize = SetModalPopupPosition;

function SetModalPopupPosition() {
    if (null == document.getElementById(_PopupID)) return;
    $('#' + _PopupID).Center();
    if ($('#' + _PopupID).is(':visible')) {
        $('#divShadow').Center();
        CreteBlockingContainer();
    }
}

jQuery.fn.Center = function () {
    //this.css("position", "absolute");
    //var top = ($(window).height() - this.height()) / 2 + ($(window).height() - $(window).scrollTop() - this.height()) / 2;
    //var left = ($(window).width() - this.width()) / 2 + $(window).scrollLeft();

    this.css("top", "50%");
    this.css("left", "50%");
    this.css('margin-left', -(this.width() / 2) + 'px');
    this.css('margin-top', -((this.height() / 2) + 0) + 'px');
    return this;
}
/*Modal Popup Section Ends*/

/*Ajax Start*/
var _ErrorMessageClass = 'ErrorMessageBox';
var _SuccessMessageClass = 'MessageBox';
var DEFAULT_DLL_ELEMENT = '<option value=""></option>';

function OnAjax_Error(error) {
    HideProgressAnimation();
    alert(error.get_message());
    //HideProgress();
}
function OnAjax_TimeOut() {
    HideProgressAnimation();
    alert('Operation TimeOut');
    //HideProgress();
}
var CONFIRMATION_MSG_CUSTOM_ATTR = 'ConfirmationMessage';
function ShowSaveConfirmation(btnElement) {
    var validationGroup = $(btnElement).attr('ValidationGroupName');
    if (validationGroup.length > 0)
        Page_ClientValidate(validationGroup);
    else
        Page_ClientValidate();

    if (Page_IsValid) {
        return confirm($(btnElement).attr(CONFIRMATION_MSG_CUSTOM_ATTR));
    }
    return false;
}
/*Ajax End*/
/* Submenu Section Start */
$(document).ready(function () {
    //    var position = $('#childpagebody').position();
    //    if (position != null) {
    //        $('.SubMenuContainer').each(function() {
    //            $(this).css('left', position.left).css('top', position.top);
    //        });
    //        $('.SubMenuItemContainer').css('left', position.left).css('top', position.top);
    //    }
    //alert('I am here' + $("input[type=text]").length);
    SetReadOnlyTextBoxStyle();
    SetDisabledButtonStyle();
});
function SetReadOnlyTextBoxStyle() {
    $('body input[type=text]').each(function () {
        if ($(this).attr('readonly'))
            $(this).removeClass('TextBoxCommon').addClass('ReadOnlyTextBox');
    });
}
function SetDisabledButtonStyle() {
    $('body input[type=submit]').each(function () {
        if ($(this).attr('disabled'))
            $(this).removeClass('ButtonCommon').removeClass('ButtonInActive').addClass('ButtonDisabled');
    });
}
function SetHeight() {
    if (window.parent != null) {
        window.parent.SetFrameHeight(0);
        window.parent.SetFrameHeight($(document).height());
    }
}
function IsNumeric(input) {

    var result = (input - 0) == input && input.length > 0;
    alert('Param Value: ' + input + ' and Result is: ' + result);
    return result;
}

function IsNumeric2(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}
function PadLeft(txtElement, length) {
    var value = $(txtElement).val();
    if (value.length > 0 && value.length < length) {
        var fillCount = length - value.length;
        for (i = 0; i < fillCount; i++) {
            value = '0' + value;
        }
    }
    $(txtElement).val(value);
}
var _DeleteURL = '';
function ShowConfirmationPopup(title, message) {
    $('#divConfirmationPopupTitle').html(title);
    $('#divConfirmationPopUpBody').html(message);
    ShowModalPopup('divModalConfirm', '', '');
}
function ConfirmDelete(url, message) {
    //ShowConfirmationPopup('Delete Data', message);
    //_DeleteURL = url;
    if (confirm(message) == true)
        window.location = url + '&Rnd=' + GetRandomNumber();
}
function SendToDeleteUrl() {
    if (_DeleteURL.length > 0) {
        var url = _DeleteURL + '&Rnd=' + GetRandomNumber();
        window.location = url;
    }
}
function DeleteDenied(message) {
    ShowConfirmationPopup('Delete Data', message);
}
///Compares two dates of dd/MM/yyyy format
//Returns 1 if value1 is greater than value2
//Returns -1 if value1 is less than value2
//Returns 0 if value1 and value2 are equal
function CompareDates(value1, value2) {
    var dateSeparator = '/';
    var date1, date2;
    var month1, month2;
    var year1, year2;
    if (DATE_FORMAT == 'mm/dd/yyyy') {
        month1 = value1.substring(0, value1.indexOf(dateSeparator));
        date1 = value1.substring(value1.indexOf(dateSeparator) + 1, value1.lastIndexOf(dateSeparator));
        year1 = value1.substring(value1.lastIndexOf(dateSeparator) + 1, value1.length);

        month2 = value2.substring(0, value2.indexOf(dateSeparator));
        date2 = value2.substring(value2.indexOf(dateSeparator) + 1, value2.lastIndexOf(dateSeparator));
        year2 = value2.substring(value2.lastIndexOf(dateSeparator) + 1, value2.length);
    }
    else {
        date1 = value1.substring(0, value1.indexOf(dateSeparator));
        month1 = value1.substring(value1.indexOf(dateSeparator) + 1, value1.lastIndexOf(dateSeparator));
        year1 = value1.substring(value1.lastIndexOf(dateSeparator) + 1, value1.length);

        date2 = value2.substring(0, value2.indexOf(dateSeparator));
        month2 = value2.substring(value2.indexOf(dateSeparator) + 1, value2.lastIndexOf(dateSeparator));
        year2 = value2.substring(value2.lastIndexOf(dateSeparator) + 1, value2.length);
    }

    if (year1 > year2)
        return 1;
    else if (year1 < year2)
        return -1;
    else if (month1 > month2)
        return 1;
    else if (month1 < month2)
        return -1;
    else if (date1 > date2)
        return 1;
    else if (date1 < date2)
        return -1;
    else
        return 0;
}
function ShowCenteredPopUp(pageURL, windowName, width, height, isScrolling) {
    var scrollbars = isScrolling ? 'yes' : 'no';
    //    if (screen.width <= 1100 && pageURL.toLowerCase().indexOf('singleview.aspx') > -1) {
    //        scrollbars = 'yes';
    //        height += 15;
    //    }
    var leftPosition = (screen.width) ? (screen.width - width) / 2 : 0;
    var topPosition = (screen.height) ? (screen.height - height) / 2 : 0;
    topPosition -= 30;
    var settings = 'height=' + height + ',width=' + width + ',top=' + topPosition + ',left=' + leftPosition + ',resizable=no,scrollbars=' + scrollbars + ',menubar=no,toolbar=no,status=yes,location=no,directories=no,addressbar=no'
    var page = pageURL;
    win = window.open(page, windowName, settings);
    if (win != null) {
        win.window.focus();
    }
    return win;
}


function CreateBlockForAnElement(elementID) {
    var blockingID = elementID + ' _Blocking';
    var element = $('#' + elementID);
    var html = '<div id="' + blockingID + '" class="blockingContainer" style="position:absolute; z-index:19; width: ' + element.width() + 'px; height: ' + element.height() + 'px; left: ' + element.position().left + 'px; top: ' + element.position().top + 'px;"></div>';
    $('body').append(html);
    $('#' + blockingID).show();
}

var _AnimationContainerID = 'divAnimationContainer';
function ShowProgressAnimation(elementID, left, top) {
    var element = $('#' + elementID);
    var position = element.position();
    left = position.left + left;
    top = position.top + top;
    if ($('#' + _AnimationContainerID).length == 0) {
        var html = '<div id="' + _AnimationContainerID + '" style="position:absolute; z-index:19; display:none; width: 100px; height: 15px; left: ' + left + 'px; top: ' + top + 'px;"><img src="/Images/Loading.gif" /></div>';
        $('body').append(html);
    }
    $('#' + _AnimationContainerID).show();
}
function ShowCenteredProgressAnimation() {    
    if ($('#' + _AnimationContainerID).length == 0) {
        var html = '<div id="' + _AnimationContainerID + '" style="position:fixed; z-index:19; display:none; width: 100px; height: 15px; margin-left:-50px; margin-top:-8px; top:50%; left:50%;"><img src="/Images/Loading.gif" /></div>';
        $('body').append(html);        
    }
    $('#' + _AnimationContainerID).show();
}
function HideProgressAnimation() {
    $('#' + _AnimationContainerID).hide();
}
function MoveToStep(stepNumber, stepCount, validationGroup) {
    HideProgressAnimation();
    var showHideSteps = true;
    if (validationGroup.length > 0)
        showHideSteps = Page_ClientValidate(validationGroup);
    if (showHideSteps) {
        for (i = 1; i <= stepCount; i++)
            $('#divStep_' + i).hide();
        $('#divStep_' + stepNumber).show();
    }
    $('html, body').animate({ scrollTop: 0 }, 'slow');
}
function SelectDeselect(anchor, tableID) {
    if ($(anchor).html() == 'Select All') {
        $("#" + tableID + " input[type='checkbox']").each(function (i) {
            $(this).attr('checked', true);
        });
        $(anchor).html('Clear All');
    }
    else {
        $("#" + tableID + " input[type='checkbox']").each(function (i) {
            $(this).attr('checked', false);
        });
        $(anchor).html('Select All');
    }
}
/********* Common Validation Functions */
var DATE_FORMAT = 'mm/dd/yy'; //Default Value
function ValidateDate(sender, args) {
    args.IsValid = false;
    try {
        var dateToCheck = args.Value;
        dateToCheck = $.datepicker.parseDate(DATE_FORMAT, dateToCheck);
        args.IsValid = true;
    }
    catch (Error) {
        args.IsValid = false;
    }
}
function ValidatAreaSelection(sender, args) {
    if ($("input[name='chkPreferredZone']:checked").length > 0)
        args.IsValid = true;
    else
        args.IsValid = false;
}
/******** Common Validation Functions End */

/******* Ajax Methods ****************/
function GetPreferredZones(ddl) {
    if ($(ddl).val().length == 0)
        $('#divPreferredArea').html('');
    else {
        ShowProgressAnimation($(ddl).attr('id'), $(ddl).width() + 5, 0);
        AjaxService.GetZonesOfCity($(ddl).val(), GetZone_Success, OnAjax_Error, OnAjax_TimeOut);
    }
}
function GetZone_Success(result) {
    HideProgressAnimation();
    var zones = eval(result);
    var output = new Sys.StringBuilder();
    for (i = 0; i < zones.length; i++) {
        var zone = zones[i];
        output.append('<div>');
        output.append(String.format('<input type="checkbox" id="chkPreferredZone_{0}" name="chkPreferredZone" value="{1}" /><label for="chkPreferredZone_{0}">{2}</label>', i, zone.ID, zone.Name));
        output.append('</div>');
    }
    $('#divPreferredArea').html(output.toString());
    //$('#trPreferredArea').show();
}
var _CityDropdown = null;
function GetCitiesByCountry(ddlCountry, ddlCity) {   
    $(ddlCity).find('option').remove();
    _CityDropdown = ddlCity;
    if ($(ddlCountry).val().length > 0) {        
        ShowProgressAnimation($(ddlCountry).attr('id'), $(ddlCountry).width() + 5, 0);
        AjaxService.GetCitiesByCountry($(ddlCountry).val(), GetCities_Success, OnAjax_Error, OnAjax_TimeOut)
    }
}
function GetCities_Success(result) {
    HideProgressAnimation();
    var cities = eval(result);
    if (cities != null && cities.length > 0) {
        $(_CityDropdown).append($("<option></option>").attr("value", '').text(''));
        for (i = 0; i < cities.length; i++) {
            var city = cities[i];
            $(_CityDropdown).append($("<option></option>").attr("value", city.ID).text(city.Name));
        }
    }
}
var _ZoneDropDownlist = null;
function BindZoneWithDropdownList(ddlCity, ddlZone) {
    $(ddlZone).find('option').remove();
    _ZoneDropDownlist = ddlZone;
    if ($(ddlCity).val().length > 0) {
        ShowProgressAnimation($(ddlCity).attr('id'), $(ddlCity).width() + 5, 0);
        AjaxService.GetZonesOfCity($(ddlCity).val(), Zone_Success, OnAjax_Error, OnAjax_TimeOut);
    }
}
function Zone_Success(result) {
    HideProgressAnimation();
    var zones = eval(result);
    if (zones.length > 0) {
        $(_ZoneDropDownlist).append($("<option></option>").attr("value", '').text(''));
        for (i = 0; i < zones.length; i++) {
            var zone = zones[i];
            $(_ZoneDropDownlist).append($("<option></option>").attr("value", zone.ID).text(zone.Name));
        }
    }
}
function ShowLargeImage(imgElement) {
    $('#imgImageViewer').attr('src', '/Images/Loading.gif');
    ShowModalPopup('divModalConfirm', 'Image Viewer', '', true)
    $('#imgImageViewer').attr('src', $(imgElement).attr('LargeImage'));
}
function CloseImageViewer(){
    HideModalPopup();
    $('#imgImageViewer').attr('src', '/Images/Loading.gif');
}
/******** Ajax Methods ****************/
$(document).ready(function () {
    $('.ListItem').each(function () {
        $(this).click(function () {
            var link = $(this).find('a').attr('href');
            if (link != null && link.length > 0)
            //window.location = link + '&Rnd=' + GetRandomNumber();
                window.open(link + '&Rnd=' + GetRandomNumber(), '', '');
        });
    });
    $('.ListItem a').click(function (event) { event.stopPropagation(); });
});



